package com.apimarket.controller;

import com.apimarket.entity.Result;
import com.apimarket.entity.SysUser;
import com.apimarket.entity.vo.JsonResult;
import com.apimarket.entity.vo.SysUserMenuVo;
import com.apimarket.service.SysUserService;
import com.apimarket.util.RandomValidateCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.rpc.ServiceException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author ZXR
 * @Date 2021/7/20 9:48
 * @Version 1.0
 */

@RequestMapping("/user")
@RestController
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @RequestMapping("/selectByName")
    public Result<SysUser> selectByName(String userName){
        SysUser sysUser = sysUserService.selectByName(userName);
        return new Result<>(sysUser,200,"根据名称查询用户成功");
    }

    @RequestMapping("doSaveObject")
    public JsonResult doSaveObject(
            SysUser entity,
            Integer[] roleIds) throws IOException, URISyntaxException {
        sysUserService.saveObject(entity,roleIds);
        return new JsonResult("save ok");
    }

    @RequestMapping("doDeleteObject")
    public JsonResult deleteObject(String userName) throws IOException, URISyntaxException {
        sysUserService.deleteObject(userName);
        return new JsonResult("delete ok");
    }
    @RequestMapping("doUpdateObject")
    public JsonResult doUpdateObject(SysUser entity,Integer[] roleIds){
        sysUserService.updateObject(entity,roleIds);
        return new JsonResult("update ok");
    }
    @RequestMapping("doValidById")
    public JsonResult doValidById(Integer id,Integer enabled) throws ServiceException {

        sysUserService.validById(id,enabled);
        return new JsonResult("update ok");
    }


    @RequestMapping("doFindPageObjects")
    public JsonResult doFindPageObjects(
            String userName,Integer page,Integer pageSize) throws ServiceException {
        return new JsonResult(
                sysUserService.findPageObjects(userName,page,
                        pageSize));
    }

    @RequestMapping("UpdatePassword")
    public JsonResult UpdatePassword(String userName,
                                     String oldPassword, String passwordA,
                                     String passwordB) throws ServiceException {
        try {
            sysUserService.UpdatePassword(userName,
                    passwordA,passwordB);
        }
        catch (ServiceException e){
            return new JsonResult(e);
        }
        return new JsonResult("update ok");
    }

    @RequestMapping("showMenus")
    public Result showMenus(){
        User userDetails=(User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser sysUser = sysUserService.selectByName(userDetails.getUsername());
        List<SysUserMenuVo> userMenusByUserId = sysUserService.findUserMenusByUserId(sysUser.getId());
        Result<List<SysUserMenuVo>> result=new Result<>(userMenusByUserId,
                200,"成功");
        return result;
    }

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            System.out.println("获取验证码失败>>>> "+ e);
        }
    }

    /**
     * 忘记密码页面校验验证码
     */
    @RequestMapping(value = "/checkVerify", method = RequestMethod.POST, headers = "Accept=application/json")
    public JsonResult checkVerify(@RequestBody Map<String, Object> requestMap, HttpSession session) {
        try{
            //从session中获取随机数,就是用户输入的
            String inputStr = requestMap.get("inputStr").toString();
            String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
            if (random == null) {
                return new JsonResult("Verify error");
            }
            if (random.equals(inputStr)) {
                return new JsonResult("Verify right");
            } else {
                return new JsonResult("Verify error");
            }
        }catch (Exception e){
            System.out.println("验证码校验失败");
            return new JsonResult("Verify error");

        }
    }

    @RequestMapping(value = "/userRegister", method = RequestMethod.POST,
            headers = "Accept=application/json")
    public JsonResult userRegister(@RequestBody Map<String, Object> requestMap
            , HttpSession session) throws IOException, URISyntaxException {
        String checkCode = requestMap.get("checkCode").toString();
        String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");

        String userName = requestMap.get("userName").toString();
        String passwordA = requestMap.get("passwordA").toString();
        String passwordB = requestMap.get("passwordB").toString();
        String email=new String();
        if (requestMap.get("email")==null){
            email=null;
        }
        else{
            email = requestMap.get("email").toString();
        }
        String telephone=new String();

        if (requestMap.get("telephone")==null){
            telephone=null;
        }
        else{
            telephone = requestMap.get("telephone").toString();
        }
        boolean gender = (Boolean) requestMap.get("gender");

        // 验证码校验

        if (!sysUserService.checkVerify(checkCode,random)){
            return new JsonResult(500,"验证码错误");
        }

        // 检验用户有没有注册
        if (sysUserService.checkUserExist(userName)){
            return new JsonResult(500,"用户已注册");
        }
        if (!passwordA.equals(passwordB)){
            return new JsonResult(500,"两次密码不一致");
        }
        //
        sysUserService.userRegister(userName, passwordA, email, telephone,
                gender);
        // 密码加密


        return new JsonResult(userName);

    }

    @RequestMapping("test")
    public JsonResult test(String userName){
        if (!sysUserService.checkUserExist(userName)){
            return new JsonResult("用户已注册");
        }
        else
            return new JsonResult(500,"caole");

    }

}
